package com.yuanlun.elasticsearch.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuanlun.elasticsearch.entity.News;
import org.apache.http.util.EntityUtils;
import org.assertj.core.util.Lists;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName NewsController
 * @Description TODO
 * @Author zxw
 * @DATE 2021/5/8 14:34
 * Version 1.0
 **/
@RestController
@RequestMapping("/news")
@CrossOrigin(origins = "*")
public class NewsController {
    @Autowired
    private RestHighLevelClient elasticsearchClient;

    @GetMapping("/tips")
    public Object autoComplete(String term) throws IOException {
        Request request = new Request("GET", "news/_search");

        request.setJsonEntity(String.format("{\n" +
                "  \"_source\": false,\n" +
                "  \"suggest\": {\n" +
                "    \"news_tags_suggest\": {\n" +
                "      \"prefix\":\"%s\",\n" +
                "      \"completion\":{\n" +
                "        \"field\":\"tags\",\n" +
                "        \"size\":10,\n" +
                "        \"skip_duplicates\":true\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}",term));
        Response response = elasticsearchClient.getLowLevelClient().performRequest(request);
        String jsonString = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        JSONArray suggest = jsonObject.getJSONObject("suggest").getJSONArray("news_tags_suggest");
        JSONArray options = suggest.getJSONObject(0).getJSONArray("options");
        List<String> results= Lists.newArrayList();
        for (int i = 0; i < options.size(); i++) {
            JSONObject opt = options.getJSONObject(i);
            results.add(opt.getString("text"));
        }
        return results;
    }

    @GetMapping("/search")
    public List<News> query(String text) throws IOException {
        /**
         * 1.对于高亮的数据，ES是抽取一个个片段，然后将这些片段设置到一个数组中
         * 2.
         */
        Request request = new Request("GET", "news/_search");
        request.setJsonEntity(String.format("{\n" +
                "  \"_source\": [\"url\",\"title\",\"content\"],\n" +
                "  \"query\": {\n" +
                "    \"multi_match\": {\n" +
                "      \"query\": \"%s\",\n" +
                "      \"fields\": [\"title\",\"content\"]\n" +
                "    }\n" +
                "  },\n" +
                "  \"highlight\": {\n" +
                "    \"pre_tags\": \"<span class='highLight'>\",\n" +
                "    \"post_tags\": \"</span>\",\n" +
                "    \"fields\": {\n" +
                "      \"title\": {}, \n" +
                "      \"content\": {}\n" +
                "    }\n" +
                "  }\n" +
                "}\n",text));
        Response response = elasticsearchClient.getLowLevelClient().performRequest(request);
        JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
        JSONArray hits = jsonObject.getJSONObject("hits").getJSONArray("hits");

        List<News> results=new ArrayList<>();
        for (int i = 0; i < hits.size(); i++) {
            News news = new News();
            JSONObject hit = hits.getJSONObject(i);
            //获取高亮的数据结果
            JSONObject highlight = hit.getJSONObject("highlight");
            //原始数据
            JSONObject source = hit.getJSONObject("_source");
            //获取高亮的数组
            JSONArray highLightTitle = highlight.getJSONArray("title");
            JSONArray highLightContent = highlight.getJSONArray("content");
            if (null!=highLightTitle){
                StringBuffer highLightTitleStringBuffer = new StringBuffer();
                for (int j = 0; j < highLightTitle.size(); j++) {
                    String titleSegment = highLightTitle.getString(j);
                    highLightTitleStringBuffer.append(titleSegment);
                }
                news.setTitle(highLightTitleStringBuffer.toString());
            }else {
                //如果不存在高亮的数据，就取原始的数据
                news.setTitle(source.getString("title"));
            }

            if (null!=highLightContent){
                StringBuffer highLightContentStringBuffer = new StringBuffer();
                for (int j = 0; j < highLightContent.size(); j++) {
                    String contentSegment = highLightContent.getString(j);
                    highLightContentStringBuffer.append(contentSegment);
                }
                news.setContent(highLightContentStringBuffer.toString());
            }else {
                //如果不存在高亮的数据，就取原始的数据
                news.setContent(source.getString("content"));
            }
            news.setUrl(source.getString("url"));
            results.add(news);
        }
        return results;
    }

}
